﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace RattlerRace
{
    [XmlRoot("Scoreboard")]
    public class Scoreboard
    {
        [XmlArray("AllPoints")]
        
        [XmlArrayItem("HallOfFame",typeof(Points))]
        private List<Points> _hallOfFame;

        [XmlArrayItem("Today", typeof(Points))]
        private List<Points> _today;

        [XmlElement("Date",typeof(DateTime))]
        private DateTime _dateToday;

        public Scoreboard()
        {
            _hallOfFame = new List<Points>();
            _today = new List<Points>();
            _dateToday = DateTime.Now;
        }

        public List<Points> HallOfFame
        {
            get { return _hallOfFame; }
            set { _hallOfFame = value; }
        }

        public List<Points> Today
        {
            get { return _today; }
            set { _today = value; }
        }

        public DateTime DateToday
        {
            get { return _dateToday; }
            set { _dateToday = value; }
        }

        /// <summary>
        /// Pomožna privatna metoda, ki jo uporabljamo pri posodobitvi scoreboarda.
        /// Njena naloga je, da napolni sezname trenutnih točk z podatki iz datotek
        /// </summary>
        //private void fillLists()
        //{
            /*
            this.HallOfFame.Clear();
            this.Today.Clear();
            StreamReader sr = new StreamReader("Tocke.xml");
            XmlSerializer xs = new XmlSerializer(typeof(Scoreboard), "");
             */
            /*
            StreamReader sr = new StreamReader("HallOfFame.txt");
            string prebrano = sr.ReadToEnd();
            Points temp;

            if (prebrano != "")
            {
                string[] hof = prebrano.Split(' ');

                for (int i = 0; i < hof.Length; i = i + 2)
                {
                    temp = new Points(hof[i], Int32.Parse(hof[i + 1]));
                    this.HallOfFame.Add(temp);
                }
            }

            sr = new StreamReader("Today.txt");
            prebrano = sr.ReadToEnd();

            if (prebrano != "")
            {
                string[] tod = prebrano.Split(' ');

                string[] date = tod[0].Split('.');
                DateTime fileDate = new DateTime(Int32.Parse(date[2]), Int32.Parse(date[1]), Int32.Parse(date[0]));

                if ((fileDate.Day == this.DateToday.Day) &&
                    (fileDate.Month == this.DateToday.Month) &&
                    (fileDate.Year == this.DateToday.Year))
                {

                    for (int i = 1; i < tod.Length; i = i + 2)
                    {
                        temp = new Points(tod[i], Int32.Parse(tod[i + 1]));
                        this.Today.Add(temp);
                    }
                }
            }
            */

        //}

        /// <summary>
        /// Pomožna privatna metoda, ki jo uporabljamo pri posodobitvi scoreboarda.
        /// Njena naloga je da zapiše trenutna (urejena in posodobljena) seznama točk v datoteko.
        /// </summary>
        //private void toFile()
        //{
           /* XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
            xsn.Add("","");
            StreamWriter sw = new StreamWriter("Tocke.xml", false);
            XmlSerializer serializer = new XmlSerializer(typeof(Scoreboard), "");
            serializer.Serialize(sw, this.GetType(), xsn);
            sw.Close();
            
            string hof = "";
            foreach (Points p in this.HallOfFame)
            {
                hof = hof + p.Player + " " + p.CurrentPoints.ToString() + " ";
            }
            hof = hof.Substring(0, hof.Length - 1);

            string tod = this.DateToday.Day.ToString() + "." + this.DateToday.Month.ToString() + "." + this.DateToday.Year.ToString() + " ";
            foreach (Points p in this.Today)
            {
                tod = tod + p.Player + " " + p.CurrentPoints.ToString() + " ";
            }
            tod = tod.Substring(0, tod.Length - 1);

            StreamWriter sw = new StreamWriter("HallOfFame.txt");
            sw.Write(hof);
            sw = new StreamWriter("Today.txt");
            sw.Write(tod);
              */

        //}
        /// <summary>
        /// Metoda se pokliče po zaključeni igri. Kot parameter prejme objekt razreda Points, ki vsebuje ime igralca in dosežene točke.
        /// Namen metode je, da posodobi scoreboarde, če je uporabnik dosegel dovolj točk, da je premagal katerega od že obstoječih uporabnikov na
        /// scoreboardu.
        /// </summary>
        /// <param name="tocke"></param>
        public void runScoreboard(Points rezultat)
        {
            /*
             * KOMENTAR
             * Ustvaril sem svojo metodo, ki prejme objekt razreda tocke, ki že vsebuje ime igralca, 
             * nato pa ga vstavi v hall of fame in/ali današnji scoreboard, če je premagal katerega od že obstoječih igralcev
             */

            //this.fillLists();

            if (this.Today.Count == 0)
            {
                this.Today.Add(rezultat);
            }
            else
            {
                for (int i = 0; i < this.Today.Count; i++)
                {
                    if (rezultat.CurrentPoints > this.Today.ElementAt(i).CurrentPoints)
                    {
                        this.Today.Insert(i, rezultat);
                        break;
                    }
                    this.Today.Add(rezultat);
                }
            }

            if (this.HallOfFame.Count == 0)
            {
                this.HallOfFame.Add(rezultat);
            }
            else
            {
                for (int i = 0; i < this.HallOfFame.Count; i++)
                {
                    if (rezultat.CurrentPoints > this.HallOfFame.ElementAt(i).CurrentPoints)
                    {
                        this.HallOfFame.Insert(i, rezultat);
                        break;
                    }
                    this.HallOfFame.Add(rezultat);
                }
            }

            if (this.Today.Count > 5)
            {
                this.Today.RemoveRange(5, this.Today.Count - 5);
            }

            if (this.HallOfFame.Count > 5)
            {
                this.HallOfFame.RemoveRange(5, this.HallOfFame.Count - 5);
            }

            //this.toFile();
        }

        /// <summary>
        /// Prepiše prejšnjo datoteko s točkami.
        /// Denis Jakoša
        /// </summary>
        public static void clearScores()
        {
            // DODAJ POT DO DATOTEKE, KJER BODO SHRANJENE TOČKE!!!!!!!!
            string scoreFilePath = "../../scores.xml";

            try
            {
                File.Create(scoreFilePath).Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        public bool checkIfReachedScoreboard(int points)
        {
            bool reached = false;
            foreach (Points p in this._hallOfFame)
            {
                if (points > p.CurrentPoints)
                {
                    return true;
                }
            }
            foreach (Points p in this._today)
            {
                if (points > p.CurrentPoints)
                {
                    return true;
                }
            }
            return reached;
        }
    }
}

